package commoditymanagement;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class CommodityDaoImpl implements CommodityDao{
	
	private List<Commodity> commodities;
	
	public CommodityDaoImpl() {
		commodities = new ArrayList<>();
	}

	@Override
	public boolean insert(Commodity c) {
		// 如果集合中有相同id商品，就返回false
		if (commodities.contains(c)) {
			return false;
		}else {
			return commodities.add(c);
		}
	}

	@Override
	public boolean remove(int id) {
		for (int i = 0,j = commodities.size(); i < j ; i++) {
			if (commodities.get(i).getId() == id) {
				// 根据id删除
				commodities.remove(i);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean update(Commodity c) {
		int i = commodities.indexOf(c);
		if (i == -1) {
			return false;
		} else {
			// 更新
			commodities.set(i, c);
			return true;
		}
	}

	@Override
	public Commodity selectById(int id) {
		for (int i = 0,j = commodities.size(); i < j ; i++) {
			if (commodities.get(i).getId() == id) {
				return commodities.get(i);
			}
		}
		return null;
	}

	@Override
	public List<Commodity> selectByPrice(BigDecimal low, BigDecimal high) {
		List<Commodity> copy = new ArrayList<>();
		for (int i = 0,j = commodities.size(); i < j ; i++) {
			BigDecimal price = commodities.get(i).getPrice();
			if (price.compareTo(low) >= 0 && price.compareTo(high) <=0) {
				copy.add(commodities.get(i));
			}
		}
		return copy;
	}

	@Override
	public List<Commodity> selectAll() {
		return commodities;
	}

	@Override
	public List<Commodity> selectByName(String name) {
		List<Commodity> copy = new ArrayList<>();
		for (int i = 0,j = commodities.size(); i < j ; i++) {
			if (commodities.get(i).getName().contains(name)) {
				copy.add(commodities.get(i));
			}
		}
		return copy;
	}

	@Override
	public List<Commodity> selectByType(CommodityType type) {
		List<Commodity> copy = new ArrayList<>();
		for (int i = 0,j = commodities.size(); i < j ; i++) {
			if (commodities.get(i).getType() == type) {
				copy.add(commodities.get(i));
			}
		}
		return copy;
	}

}
